package com.ali.service.impl;

import com.ali.common.BeanCopyUtil;
import com.ali.dao.AuthorMapper;
import com.ali.dao.ShiMapper;
import com.ali.dto.AuthorInfo;
import com.ali.dto.PageInfo;
import com.ali.dto.ShiInfo;
import com.ali.entity.Author;
import com.ali.entity.Shi;
import com.ali.service.ShiService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ShiServiceImpl implements ShiService {
    @Resource
    private ShiMapper shiMapper;
    @Resource
    private AuthorMapper authorMapper;

    @Override
    public PageInfo<ShiInfo> query(String pageNo, String pageSize) {
        PageInfo<ShiInfo> pageInfo = new PageInfo<>();
        pageInfo.setPageNo(pageNo);
        pageInfo.setPageSize(pageSize);

        Page<Shi> page = new Page<>(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        QueryWrapper<Shi> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        Page<Shi> resultPage = shiMapper.selectPage(page, queryWrapper);
        List<Shi> shis = resultPage.getRecords();
        List<ShiInfo> shiInfos = BeanCopyUtil.copyListProperties(shis, ShiInfo::new);
        for (ShiInfo shiInfo : shiInfos) {
            AuthorInfo authorInfo = getAuthorInfo(shiInfo.getAuthorCode());
            shiInfo.setAuthorInfo(authorInfo);
        }

        pageInfo.setTotal(String.valueOf(resultPage.getTotal()));
        pageInfo.setData(shiInfos);
        return pageInfo;
    }

    /**
     * 根据作者code获取作者信息
     */
    private AuthorInfo getAuthorInfo(String authorCode) {
        QueryWrapper<Author> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", authorCode);
        Author author = authorMapper.selectOne(queryWrapper);
        AuthorInfo authorInfo = new AuthorInfo();
        BeanUtils.copyProperties(author, authorInfo);
        return authorInfo;
    }
}